package com.bjb.vr.common.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjb.vr.common.ao.ResContentAo;
import com.bjb.vr.common.ao.ResPlatformAo;
import com.bjb.vr.common.constant.ResDicType;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.*;
import com.bjb.vr.common.mapper.ResPlatformResourceMapper;
import com.bjb.vr.common.utils.DateTimeUtil;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.ResPlatformVo;
import com.bjb.vr.common.vo.UmsAccountVo;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author admin
 * @description 针对表【res_platform_resource】的数据库操作Service实现
 * @createDate 2022-03-22 15:52:49
 */
@Service
public class ResPlatformResourceService extends ServiceImpl<ResPlatformResourceMapper, ResPlatformResource> {

    @Autowired
    private ResPlatformResourceMapper platformResourceMapper;


    /**
     * 通过授权界面增加平台资源
     * @param contentIds  授权的课程内容id数组
     * @param tenantId    授权的租户id
     * @return
     */
    public boolean addResPlatResourceByContentAuthority(Long[] contentIds,String tenantId){
        List<ResPlatformResource> resPlatformResourceList = platformResourceMapper.queryResPlatResourceByContentAuthority(contentIds,tenantId);
        this.saveBatch(resPlatformResourceList);
        return true;
    }

    /**
     * 查询平台资源
     *
     * @param resPlatformAo
     * @return
     */
    public IPage<ResPlatformVo> getPlatformResources(ResPlatformAo resPlatformAo) {
        SysPlatform sysPlatform = (SysPlatform) ThreadLocalUtil.get(ThreadLocalConstant.USER_PLATFORM_INFO);
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        // 构造查询条件
        MPJLambdaWrapper<ResPlatformVo> joinQueryWrapper = new MPJLambdaWrapper<>();
        joinQueryWrapper
                .select(ResPlatformResource::getId)
                .select(ResPlatformResource::getResId)
                .select(ResPlatformResource::getResName)
                .select(ResPlatformResource::getPeriod)
                .select(ResPlatformResource::getLevel)
                .select(ResPlatformResource::getSubject)
                .select(ResPlatformResource::getResType)
                .select(ResPlatformResource::getThemeCode)
                .select(ResContentAuthority::getContValidStartDate)
                .select(ResContentAuthority::getContValidEndDate)
                .selectAs(ResPlatformResource::getContentSize, "capacity")
                .innerJoin(ResContentAuthority.class,on->on.eq(ResContentAuthority::getContentId, ResLocalResource::getResId)
                        .eq(ResContentAuthority::getTenantId, umsAccountVo.getTenantId())
                ).groupBy(ResPlatformResource::getResId);
        // 查询条件
        joinQueryWrapper.eq(Objects.nonNull(sysPlatform.getPlatformCode()), ResPlatformResource::getThemeCode, sysPlatform.getPlatformCode());
        joinQueryWrapper.eq(Objects.nonNull(resPlatformAo.getPeriod()), ResPlatformResource::getPeriod, resPlatformAo.getPeriod());
        joinQueryWrapper.eq(Objects.nonNull(resPlatformAo.getLevel()), ResPlatformResource::getLevel, resPlatformAo.getLevel());
        joinQueryWrapper.eq(Objects.nonNull(resPlatformAo.getSubject()), ResPlatformResource::getSubject, resPlatformAo.getSubject());
        joinQueryWrapper.eq(Objects.nonNull(resPlatformAo.getResType()), ResPlatformResource::getResType, resPlatformAo.getResType());
        joinQueryWrapper.like(StringUtils.isNotBlank(resPlatformAo.getResName()), ResPlatformResource::getResName, resPlatformAo.getResName());
        // 执行查询
        IPage<ResPlatformVo> joinPage = platformResourceMapper.selectJoinPage(new Page<>(resPlatformAo.getCurrent(), resPlatformAo.getSize()), ResPlatformVo.class, joinQueryWrapper);
        List<ResPlatformVo> resPlatformVoList = joinPage.getRecords();
        List<ResPlatformVo> newResPlatformVoList = convertPoToVo(resPlatformVoList);
        joinPage.setRecords(newResPlatformVoList);
        return joinPage;
    }


    public boolean updateUseCount(Long resId, String tenantId) {
        Assert.notNull(resId, "资源id不能为空");
        Assert.notNull(tenantId, "租户ID不能为空");
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("res_id", resId);
        wrapper.eq("tenant_id", tenantId);
        wrapper.setSql("use_count = use_count + 1");
        this.update(wrapper);
        return true;
    }

    /**
     * 数据类型转换
     *
     * @param oldResPlatformVoList
     * @return
     */
    private List<ResPlatformVo> convertPoToVo(List<ResPlatformVo> oldResPlatformVoList) {
        List<ResPlatformVo> resPlatformVos = new ArrayList<>();
        if (oldResPlatformVoList.isEmpty()) {
            return resPlatformVos;
        }
        oldResPlatformVoList.stream().forEach(oldResPlatformVo -> {
            ResPlatformVo resPlatformVo = new ResPlatformVo();
            BeanUtils.copyProperties(oldResPlatformVo, resPlatformVo);

            MPJLambdaWrapper<ResPlatformVo> joinQueryWrapper = new MPJLambdaWrapper<>();
            joinQueryWrapper
                    .selectCount(ResDeviceContent::getId, "installedNum")
                    .leftJoin(ResDeviceContent.class,on->on.eq(ResDeviceContent::getContentId, ResLocalResource::getResId)
                                                            .eq(ResDeviceContent::getTenantId, ResLocalResource::getTenantId));
            joinQueryWrapper.eq(ResPlatformResource::getResId, oldResPlatformVo.getResId());

            List<ResPlatformVo> list =  platformResourceMapper.selectJoinList(ResPlatformVo.class,joinQueryWrapper);
            if(list!=null && list.size()>0){
                resPlatformVo.setInstalledNum(list.get(0).getInstalledNum());
            }
            // 设置内容是否有效
            LocalDate nowDate = DateTimeUtil.getLocalDate(new Date());
            if (oldResPlatformVo.getContValidStartDate() == null) {
                resPlatformVo.setContentValidState(2);
            } else if(oldResPlatformVo.getContValidEndDate() == null){
                if (nowDate.compareTo(oldResPlatformVo.getContValidStartDate()) >= 0) {
                    resPlatformVo.setContentValidState(1);
                } else {
                    resPlatformVo.setContentValidState(2);
                }
            }else {
                if (nowDate.compareTo(oldResPlatformVo.getContValidStartDate()) >= 0 && nowDate.compareTo(oldResPlatformVo.getContValidEndDate()) <= 0) {
                    resPlatformVo.setContentValidState(1);
                } else {
                    resPlatformVo.setContentValidState(2);
                }
            }

            resPlatformVos.add(resPlatformVo);
        });
        return resPlatformVos;
    }

    public ResPlatformResource getByResId(Long resId) {
        MPJLambdaWrapper<ResPlatformResource> lambdaWrapper = new MPJLambdaWrapper<>();
        lambdaWrapper.selectAll(ResPlatformResource.class)
                .selectAs(ResPlatformResource::getResName, "name");
        lambdaWrapper.eq(Objects.nonNull(resId), ResPlatformResource::getResId, resId);
        return platformResourceMapper.selectOne(lambdaWrapper);
    }

    public ResPlatformResource queryCusResBundleResPlat(ResContentAo resContentAo){

        MPJLambdaWrapper<ResPlatformResource> lambdaWrapper = new MPJLambdaWrapper<>();
        lambdaWrapper.selectAll(ResPlatformResource.class)
                .selectAs(ResPlatformResource::getResName, "name")
                .selectAs(ResDictionary::getDictName,"themeCode")
                .leftJoin(ResDictionary.class,ResDictionary::getDictCode,ResPlatformResource::getThemeCode);
        lambdaWrapper.eq(Objects.nonNull(resContentAo.getId()), ResPlatformResource::getResId, resContentAo.getId());
        lambdaWrapper.eq(Objects.nonNull(resContentAo.getTenantId()), ResPlatformResource::getTenantId, resContentAo.getTenantId());
        return platformResourceMapper.selectOne(lambdaWrapper);
    }

}




